<template>
    <MkDrawer ref="drawerRef" headerButton="none" :title="'开发模式 : ' + r.code + ' (' + formatDate(r.updateTime) + ')'">
        <template #btn>
            <el-button type="primary" @click="reset">重置</el-button>
            <el-button type="primary" @click="printTest">打印测试</el-button>
            <el-button type="primary" @click="submit">正式提交</el-button>
        </template>
        <MkForm :model="r.model" ref="mkFormRef" :col="3">
            <el-container>
                <el-aside>
                    <MkInput label="p1" v-model="r.model.p1" :config="{ required: true, }" />
                    <MkInput label="p2" v-model="r.model.p2" />
                    <MkInput label="p3" v-model="r.model.p3" />
                </el-aside>
                <el-main style="padding: 0px 0px 0px 8px;">
                    <MkInput label="标题" v-model="r.model.title" :config="{ required: true, }" />
                    <MkInput label="说明" :col="3" :rows="3" type="textarea" placeholder="必须说明用途和参数" required
                        v-model="r.model.remark" />
                </el-main>
            </el-container>
        </MkForm>
        <span style="padding:6px" />
        <el-tabs v-model="r.activeName" type="border-card" @tab-click="tabClick">
            <el-tab-pane label="模板" name="first">
                <v-ace-editor v-model:value="r.model.template" lang="html" theme="terminal" :min-lines="30"
                    :maxLines="1000" :options="aceConfig" />
            </el-tab-pane>
            <el-tab-pane label="SQL1">
                <v-ace-editor v-model:value="r.model.sql1" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="SQL2" name="sql2">
                <v-ace-editor v-model:value="r.model.sql2" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="SQL3">
                <v-ace-editor v-model:value="r.model.sql3" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="SQL4">
                <v-ace-editor v-model:value="r.model.sql4" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="SQL5">
                <v-ace-editor v-model:value="r.model.sql5" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="预览" v-loading="r.loading" style="min-height: 100px;">
                <div style=" border: 1px solid #dcdfe6">
                    <component :is="myComp"> </component>
                </div>
                <div v-html="r.testMsg" style="white-space: pre;"></div>
            </el-tab-pane>
        </el-tabs>
    </MkDrawer>

    <MkPrintWeb :code="r.code" ref="printRef"></MkPrintWeb>
</template>

<script lang="ts" setup>
// 问卷分类新增，编辑
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
// 接口
import { BasPrintApi } from '/@/api/bas/basPrint';
import { BasPrintDraft } from '/@/api/bas/basPrint/dto';
// 工具
import { isNull, clog, showSuccess, showWarning, showError } from '/@/utils/index'
import { formatDate } from '/@/utils/formatTime'

import { VAceEditor } from 'vue3-ace-editor';
import 'ace-builds/src-noconflict/mode-html'; // Load the language definition file used below
import 'ace-builds/src-noconflict/mode-sql'; // Load the language definition file used below
import 'ace-builds/src-noconflict/theme-terminal'; // Load the theme definition file used below
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-searchbox';

import MkPrintWeb from '/@/componentsMaike/other/MkPrintWeb.vue';
import { useConfirmDialog } from '/@/hooks/useConfirmDialog';

const emits = defineEmits(['onSuccess']);

const mkFormRef = ref();
const drawerRef = ref();

const editStyle = { fontSize: '14px' }

//ace编辑器配置
const aceConfig = {
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    tabSize: 2,
    showPrintMargin: false,
    fontSize: 14,
    fontFamily: '"Consolas", "Lucida Console", "Courier New", "monospace"',
    //showGutter: true, //显示行号
    showLineNumbers: true, //显示行号
    showFoldWidgets: true, //显示折叠按钮
    //showInvisibles: true, //显示空白字符
    useWorker: false, //是否使用工作线程
}

const r = reactive({
    code: "",
    loading: false,
    model: {} as BasPrintDraft,
    updateTime: new Date(),
    testMsg: "",
    activeName: 'first',
});

const reset = () => {
    useConfirmDialog(r.code, "确定重置吗?").then(async () => {
        // 通过id从数据库获取正式表的配置,更新草稿
        var model = (await BasPrintApi().get(r.model.id)) as BasPrintDraft
        model.p1 = r.model.p1;
        model.p2 = r.model.p2;
        model.p3 = r.model.p3;
        r.model = model;
        await BasPrintApi().updateDraft(r.model);
        r.updateTime = r.model.updateTime
    })
};

// 打开弹窗
const open = async (row: any) => {
    drawerRef.value.show();
    mkFormRef.value?.resetFields();
    clog("open", row)
    r.code = row.code;
    // 从数据库读取草稿表的配置(后台判断,没有就新增一个草稿)
    r.model = await BasPrintApi().getDraft(row.id);
    r.updateTime = r.model.updateTime
    r.activeName = 'first';
};

//自定义组件
const myComp = ref()

// 预览
const tabClick = async (tab: any) => {
    if (tab.props.label == '预览') {
        if (!validate()) return;

        await BasPrintApi().updateDraft(r.model);

        //先执行空数据源验证
        //捕获加载动态组件失败的异常
        let beginTime = new Date().getTime();
        r.testMsg = "开始预览: " + beginTime;
        myComp.value = {
            setup() {
                let data = { "t1": [], "t2": [], "t3": [], "t4": [], "t5": [] };
                onActivated(() => { console.log('onActivated'); })
                onBeforeMount(() => { console.log('空数据源验证:onBeforeMount'); })
                //onBeforeUnmount(() => { console.log('onBeforeUnmount'); })
                onBeforeUpdate(() => { console.log('onBeforeUpdate'); })
                onDeactivated(() => { console.log('onDeactivated'); })
                onErrorCaptured((err, vm, info) => { console.log('onErrorCaptured'); return false; })
                onMounted(() => { console.log('onMounted'); })
                onRenderTracked(() => { console.log('onRenderTracked'); })
                onRenderTriggered(() => { console.log('onRenderTriggered'); })
                onServerPrefetch(() => { console.log('onServerPrefetch'); })
                //onUnmounted(() => { console.log('onUnmounted'); })
                onUpdated(() => { console.log('onUpdated'); })
                return data;
            },
            template: `${r.model.template}`,
        }
        nextTick(() => {
            let endTime = new Date().getTime();
            r.testMsg += "<p>结束预览: " + endTime;
            clog("验证开始", beginTime)
            clog("验证结束", endTime)
            if (endTime - beginTime > 100) {
                ElMessage.error("空数据源验证时间过长, 请检查模板是否有错误");
                r.testMsg += "<p>空数据源验证时间过长: " + (endTime - beginTime);
                r.testMsg += "<p>空数据源验证可能失败, 请修改模板";
                return;
            }
        })

        // 正式预览
        r.loading = true;
        r.updateTime = new Date();
        var res = await BasPrintApi().queryDataAndTemplateForDraft({ id: r.model.id, p1: r.model.p1, p3: r.model.p2, p2: r.model.p3 })
        let data = {
            t1: res.data.t1,
            t2: res.data.t1,
            t3: res.data.t1,
            t4: res.data.t1,
            t5: res.data.t1
        };
        clog("打印数据源:")
        clog(data)
        myComp.value = {
            setup() {
                onBeforeMount(() => { console.log('开始打印预览:onBeforeMount'); })
                return data;
            },
            template: `${r.model.template}`,
        }
        r.loading = false;
    }
}

const submit = async () => {
    // 校验
    if (!validate()) return;
    useConfirmDialog(r.code, "确定提交吗").then(async () => {
        // 保存草稿
        await BasPrintApi().updateDraft(r.model);
        // 确认草稿
        await BasPrintApi().confirmDraft({ id: r.model.id });
        drawerRef.value.close();
        showSuccess();
        emits('onSuccess');
    })
}

const validate = () => {
    if (isNull(r.model.title) || isNull(r.model.template) || isNull(r.model.sql1) || isNull(r.model.p1) || isNull(r.model.remark)) {
        ElMessage.error(" 标题、模板、SQL1、P1、说明 都不能为空");
        return false;
    }
    return true;
}

// 打印测试
const printRef = ref()

const printTest = async () => {
    if (validate())
        printRef.value.printWeb(r.model.p1, r.model.p2, r.model.p3)
}

// 导出对象
defineExpose({ open });
</script>
